<?php

namespace App\Jobs;

use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class SyncCheckSmsBalance implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $client = new Client();
        $fullUrl = 'http://shmtn.b2m.cn/simpleinter/getBalance';
        $nowStr = date('Ymdhis');
        $now = time();

        $apps = [
            "phone" => [
                "name" => '验证短信',
                "appId" => config('app.sms.emay_app_id2'),
                "secretKey" => config('app.sms.emay_secret_key2'),
                'time' => null,
                'status' => null,
                'balance' => null,
            ],
            "card" => [
                "name" => '营销短信',
                "appId" => config('app.sms.emay_app_id1'),
                "secretKey" => config('app.sms.emay_secret_key1'),
                'time' => null,
                'status' => null,
                'balance' => null,
            ]
        ];
        foreach ($apps as $action => $app) {
            $data = [
                'appId' => $app['appId'],
                'timestamp' => $nowStr,
                'sign' => md5($app['appId'] . $app['secretKey'] . $nowStr)
            ];
            $response = $client->request('GET', $fullUrl, [
                'query' => $data,
                'timeout' => 5
            ]);
            $apps[$action]['time'] = $now;
            $apps[$action]['status'] = false;
            $resp_status = $response->getStatusCode();
            if ($resp_status == 200) {
                $resp_content = $response->getBody()->getContents();
                $respObj = json_decode($resp_content, true);
                if ($respObj && isset($respObj['data']) && isset($respObj['data']['balance'])) {
                    $balance = intval($respObj['data']['balance']);
                    $apps[$action]['status'] = true;
                    $apps[$action]['balance'] = $balance;
                    Log::info($action . " => " . $balance);
                }
            }
        }
        Cache::put('appMsgBalance', $apps, 7200);
    }
}
